<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\logic;

use app\common\model\finance\PaymentRecord;
use app\common\service\FileService;
use think\facade\Db;
use app\common\model\pay\PayConfig;
use app\common\model\user\UserGroup;

/**
 * 支付/转账逻辑层
 * Class PaymentLogic
 * @package app\common\logic
 */
class PaymentLogic extends BaseLogic
{
    /**
     * @notes 创建打款记录
     * @param array $params
     * @return bool
     * @author dev
     * @date 2024/03/31 11:30
     */
    public static function create(array $params): bool
    {
        Db::startTrans();
        try {
            // 获取用户组信息
            $userGroup = UserGroup::where('id', $params['group_id'])->findOrEmpty();
            if ($userGroup->isEmpty()) {
                throw new \Exception('用户组不存在');
            }
            // 初始化服务费金额
            $service_fee_amount = 0;
            $serverU_fee_amount = 0;
            // 从用户组获取服务费率转账服务费率
            $service_fee = $userGroup->serverchargerate ?? 0;
            //扫码服务费率
            $serverUchargerate = $userGroup->serverUchargerate ?? 0;
            
            // 计算实收金额
            $deposit_amount = $params['amount'];
            
            // 当任一费率大于0时才计算服务费
            if ($service_fee > 0 || $serverUchargerate > 0) {
                // 计算转账服务费金额
                if ($service_fee > 0) {
                    $service_fee_amount = round($params['amount'] * $service_fee, 2);
                }
                
                // 计算扫码服务费金额
                if ($params['pay_way'] == 4 && $serverUchargerate > 0) {
                    $serverU_fee_amount = round($params['amount'] * $serverUchargerate, 2);
                }
                
                // 计算最终实收金额
                $deposit_amount = round($params['amount'] - $service_fee_amount - $serverU_fee_amount, 2);
                
                // 确保实收金额不小于0
                $deposit_amount = max(0, $deposit_amount);
            }

            // 创建打款记录
            PaymentRecord::create([
                'payment_date' => $params['payment_date'] ?? date('Y-m-d H:i:s'),
                'currency' => $params['currency'],
                'amount' => $params['amount'],
                'service_fee' => $service_fee,
                'service_feeamount' => $service_fee_amount, // 转账服务费金额
                'serverUchargerate' => $serverUchargerate,
                'serverUamount' => $serverU_fee_amount, // 扫码服务费金额
                'deposit_amount' => $deposit_amount,
                'account' => $params['account'] ?? '',
                'company_name' => $params['company_name'] ?? '',
                'remarks' => $params['remarks'] ?? '',
                'files' => $params['files'] ?? '',
                'status' => 0, // 默认待处理状态
                'pay_way' => $params['pay_way'], // 打款方式
                'user_id' => $params['user_id'], // 用户ID
                'group_id' => $params['group_id'], // 客户ID
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 获取打款记录列表
     * @param array $params
     * @return array
     * @author dev
     * @date 2024/03/31 11:40
     */
    public static function lists(array $params): array
    {
        $where = [];

        // 客户ID筛选
        if (!empty($params['group_id'])) {
            $where[] = ['group_id', '=', $params['group_id']];
        }
        
        // 用户ID筛选
        if (!empty($params['user_id'])) {
            $where[] = ['user_id', '=', $params['user_id']];
        }
        
        // 日期筛选
        if (!empty($params['start_date'])) {
            $where[] = ['payment_date', '>=', $params['start_date']];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['payment_date', '<=', $params['end_date']];
        }
        
        // 状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }
        
        // 币种筛选
        if (!empty($params['currency'])) {
            $where[] = ['currency', '=', $params['currency']];
        }
        
        // 账户筛选
        if (!empty($params['account'])) {
            $where[] = ['account', 'like', "%{$params['account']}%"];
        }
        
        // 分页
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;
        
        // 统计数据
        $count = PaymentRecord::where($where)->count();
        
        // 获取数据
        $list = PaymentRecord::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 处理文件路径
        foreach ($list as &$item) {
            if ($item['files']) {
                $fileArray = explode(';', $item['files']);
                $item['file_list'] = [];
                foreach ($fileArray as $file) {
                    $item['file_list'][] = [
                        'path' => $file,
                        'url' => FileService::getFileUrl($file)
                    ];
                }
            } else {
                $item['file_list'] = [];
            }
        }
        
        return [
            'count' => $count,
            'list' => $list,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * @notes 获取打款记录详情
     * @param array $params
     * @return array
     * @author dev
     * @date 2024/03/31 11:50
     */
    public static function detail(array $params): array
    {
        $where = [
            ['id', '=', $params['id']],
            ['user_id', '=', $params['user_id']]
        ];
        
        $detail = PaymentRecord::where($where)->findOrEmpty()->toArray();
        
        if (!empty($detail)) {
            // 处理文件路径
            if ($detail['files']) {
                $fileArray = explode(';', $detail['files']);
                $detail['file_list'] = [];
                foreach ($fileArray as $file) {
                    $detail['file_list'][] = [
                        'path' => $file,
                        'url' => FileService::getFileUrl($file)
                    ];
                }
            } else {
                $detail['file_list'] = [];
            }
        }
        
        return $detail;
    }

    /**
     * @notes 更新打款记录状态
     * @param array $params
     * @return bool
     * @author dev
     * @date 2024/03/31 12:00
     */
    public static function updateStatus(array $params): bool
    {
        Db::startTrans();
        try {
            $where = [
                ['id', '=', $params['id']],
                ['user_id', '=', $params['user_id']]
            ];
            
            $updateData = [
                'status' => $params['status'],
                'approval_user_id' => $params['user_id'],
                'approval_time' => date('Y-m-d H:i:s'),
                'approval_remarks' => $params['remarks'] ?? '',
            ];
            
            PaymentRecord::where($where)->update($updateData);
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 删除打款记录
     * @param array $params
     * @return bool
     * @author dev
     * @date 2024/03/31 12:10
     */
    public static function delete(array $params): bool
    {
        Db::startTrans();
        try {
            $where = [
                ['id', '=', $params['id']],
                ['user_id', '=', $params['user_id']]
            ];
            
            $record = PaymentRecord::where($where)->findOrEmpty()->toArray();
            if (empty($record)) {
                self::setError('记录不存在或无权限删除');
                return false;
            }
            
            // 删除文件
            if (!empty($record['files'])) {
                $fileArray = explode(';', $record['files']);
                foreach ($fileArray as $file) {
                    FileService::delete($file);
                }
            }
            
            PaymentRecord::where($where)->delete();
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 上传打款凭证
     * @param array $params
     * @return bool
     * @author dev
     * @date 2024/03/31 12:20
     */
    public static function uploadProof(array $params): bool
    {
        Db::startTrans();
        try {
            $where = [
                ['id', '=', $params['id']],
                ['user_id', '=', $params['user_id']]
            ];
            
            $record = PaymentRecord::where($where)->findOrEmpty()->toArray();
            if (empty($record)) {
                self::setError('记录不存在或无权限上传');
                return false;
            }
            
            // 处理文件上传
            $files = [];
            foreach ($params['files'] as $file) {
                $files[] = FileService::setFileUrl($file);
            }
            
            // 更新文件路径
            $updateData = [
                'files' => implode(';', $files),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            PaymentRecord::where($where)->update($updateData);
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 获取支付统计信息
     * @param array $params
     * @return array
     * @author dev
     * @date 2024/03/31 12:30
     */
    public static function statistics(array $params): array
    {
        $where = [];
        
        // 用户ID筛选
        if (!empty($params['user_id'])) {
            $where[] = ['user_id', '=', $params['user_id']];
        }
        
        // 日期范围
        $startDate = $params['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
        $endDate = $params['end_date'] ?? date('Y-m-d');
        
        $where[] = ['payment_date', '>=', $startDate];
        $where[] = ['payment_date', '<=', $endDate];
        
        // 统计数据
        $stats = PaymentRecord::where($where)
            ->field([
                'COUNT(*) as total_count',
                'SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as pending_count',
                'SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as confirmed_count',
                'SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as rejected_count',
                'SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as processing_count',
                'SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) as completed_count',
                'SUM(amount) as total_amount'
            ])
            ->find();
            
        // 每日交易金额
        $dailyAmount = PaymentRecord::where($where)
            ->field([
                'DATE(payment_date) as date',
                'SUM(amount) as amount'
            ])
            ->group('date')
            ->order('date', 'asc')
            ->select()
            ->toArray();
            
        return [
            'stats' => $stats,
            'daily_amount' => $dailyAmount,
            'date_range' => [
                'start_date' => $startDate,
                'end_date' => $endDate
            ]
        ];
    }
}